﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Rss.Domain;
using System.IO;

namespace RssApp.Parser
{
    /// <summary>
    /// <![CDATA[博客园RSS解析器]]>
    /// </summary>
    public class CnblogsParser : BlogParserBase,Rss.Infrastructure.IBlogParser
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rss"></param>
        /// <returns></returns>
        public IEnumerable<Blog> TryCatchBlogs(RssInfo rss)
        {
            List<Blog> list = new List<Blog>();
            string strRssXml = base.TryGetRss(rss);
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Rss.Domain.ValueObject.Feed));
            using (StringReader sr = new StringReader(strRssXml))
            {
                object o = xs.Deserialize(sr);
                Rss.Domain.ValueObject.Feed rssObj = (Rss.Domain.ValueObject.Feed)o;
                sr.Dispose();
                foreach (var item in rssObj.entrys)
                {
                    Blog blog = new Blog();
                    blog.Title = item.title;
                    blog.Url = item.id;
                    blog.Summary = item.summary;
                    blog.Category = string.Empty;
                    list.Add(blog);
                }
            }
            return list;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rss"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Blog>> TryCatchBlogsAsync(RssInfo rss)
        {
            string strRssXml = await base.TryGetRssAsync(rss);
            return await Task.Run<IEnumerable<Blog>>(() =>
            {
                List<Blog> list = new List<Blog>();
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Rss.Domain.ValueObject.Feed));
                using (StringReader sr = new StringReader(strRssXml))
                {
                    object o = xs.Deserialize(sr);
                    Rss.Domain.ValueObject.Feed rssObj = (Rss.Domain.ValueObject.Feed)o;
                    foreach (var item in rssObj.entrys)
                    {
                        Blog blog = new Blog();
                        blog.Title = item.title;
                        blog.Url = item.id;
                        blog.Summary = item.summary;
                        blog.Category = string.Empty;
                        list.Add(blog);
                    }
                    return list;
                }
            });
        }
    }
}